package com.zx.system.block.service.impl;

import com.zx.core.context.TenantContextHolder;
import com.zx.core.enums.StatusEnum;
import com.zx.core.page.PageInfo;
import com.zx.core.wrapper.ListWrapper;
import com.zx.core.wrapper.ObjectWrapper;
import com.zx.core.wrapper.PageWrapper;
import com.zx.core.wrapper.ResponseWrapper;
import com.zx.security.block.uitls.SecurityUtils;
import com.zx.system.block.dao.SysPostMapper;
import com.zx.system.block.dao.SysUserPostMapper;
import com.zx.system.block.mapstruct.PostMapStructMapper;
import com.zx.system.block.model.SysPost;
import com.zx.system.block.model.SysUserPost;
import com.zx.system.block.param.PostParam;
import com.zx.system.block.service.ISysPostService;
import com.zx.system.block.utils.SystemNoUtils;
import com.zx.system.block.vo.SysPostVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * description: 业务层岗位服务实现 <br>
 * create: 2024-08-24 11:57
 * </p>
 *
 * @author zhou  xun
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SysPostServiceImpl implements ISysPostService {
    private final SysPostMapper sysPostMapper;
    private final SysUserPostMapper sysUserPostMapper;

    /**
     * 获取岗位信息Map 用于岗位信息匹配
     *
     * @return 包含岗位标识符作为键, {@link SysPost} 对象作为值的映射表{@code Map<String, SysPost>}
     * @author zhou  xun
     * @since 2024-10-29
     */
    @Override
    public Map<String, SysPost> getPost() {
        Map<String, SysPost> map = new HashMap<>();
        List<SysPost> sysPostList = sysPostMapper.selectPostList(null, null, null, null, null, null);
        if (null != sysPostList && !sysPostList.isEmpty()) {
            //将列表转换为 Map
            for (SysPost sysPost : sysPostList) {
                map.putIfAbsent(sysPost.getId(), sysPost);
            }
        }
        return map;
    }

    /**
     * 查询岗位列表
     *
     * @param postParam 岗位参数
     * @return {@link ListWrapper<SysPost>}
     * @author zhou  xun
     * @since 2024-10-29
     */
    @Override
    public ListWrapper<SysPost> selectPostList(PostParam postParam) {
        ListWrapper<SysPost> result = new ListWrapper<>();
        try {
            List<SysPost> sysPostList = sysPostMapper.selectPostList(TenantContextHolder.getTenantId(), postParam.getPostCode(), postParam.getPostName(),
                    postParam.getStatus(), postParam.getCreateTimeStart(), postParam.getCreateTimeEnd());
            if (null != sysPostList && !sysPostList.isEmpty()) {
                result.setData(sysPostList);
            }
        } catch (Exception e) {
            log.error("查询岗位列表时发生错误", e);
            result.fail("查询岗位列表时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询岗位列表
     *
     * @param postParam 岗位参数
     * @return {@link PageWrapper<SysPost>}
     * @author zhou  xun
     * @since 2025-11-15
     */
    @Override
    public PageWrapper<SysPost> selectPostListByPage(PostParam postParam) {
        PageWrapper<SysPost> result = new PageWrapper<>();
        try {
            PageInfo pageInfo = new PageInfo(postParam.getPageNum(), postParam.getPageSize());
            postParam.setPageNum(pageInfo.getPageNum());
            postParam.setPageSize(pageInfo.getPageSize());

            Long count = sysPostMapper.getPostListCount(TenantContextHolder.getTenantId(), postParam.getPostCode(), postParam.getPostName(),
                    postParam.getStatus(), postParam.getCreateTimeStart(), postParam.getCreateTimeEnd());
            if (count > 0) {
                List<SysPost> sysPostList = sysPostMapper.getPostListByPage(TenantContextHolder.getTenantId(), postParam.getPostCode(), postParam.getPostName(),
                        postParam.getStatus(), postParam.getCreateTimeStart(), postParam.getCreateTimeEnd(),
                        postParam.getPageNum(), postParam.getPageSize());
                result.setData(sysPostList);
            }
            result.setTotal(count);
            result.setCurrentPageNum(postParam.getPageNum());
            result.setTotalPage(pageInfo);
        } catch (Exception e) {
            log.error("分页查询岗位列表时发生错误", e);
            result.fail("分页查询岗位列表时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 新增岗位
     *
     * @param postParam 岗位参数
     * @return {@link ResponseWrapper}
     * @author zhou  xun
     * @since 2024-10-29
     */

    @Override
    public ResponseWrapper addPost(PostParam postParam) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            List<SysPost> checkCodeList = sysPostMapper.selectPostList(TenantContextHolder.getTenantId(), postParam.getPostCode(), null, null, null, null);
            if (null != checkCodeList && !checkCodeList.isEmpty()) {
                if (checkCodeList.stream().anyMatch(post -> post.getPostCode().equals(postParam.getPostCode()))) {
                    result.fail("已存在相同岗位编码!");
                    return result;
                }
            }
            List<SysPost> checkNameList = sysPostMapper.selectPostList(TenantContextHolder.getTenantId(), null, postParam.getPostName(), null, null, null);
            if (null != checkNameList && !checkNameList.isEmpty()) {
                if (checkNameList.stream().anyMatch(post -> post.getPostName().equals(postParam.getPostName()))) {
                    result.fail("已存在相同岗位名称!");
                    return result;
                }
            }
            // 验证岗位状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(postParam.getStatus());
            if (null == statusEnum) {
                result.fail("传入的岗位状态错误!");
                return result;
            }
            SysPost sysPost = PostMapStructMapper.INSTANCE.postParamToSysPost(postParam);
            // 设置id
            sysPost.setId(SystemNoUtils.generateSystemId());
            sysPost.setCreateBy(SecurityUtils.getUserId());
            sysPost.setCreateTime(LocalDateTime.now());
            sysPostMapper.insert(sysPost);
        } catch (Exception e) {
            log.error("新增岗位时发生错误", e);
            result.fail("新增岗位时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑岗位
     *
     * @param postParam 岗位参数
     * @return {@link ResponseWrapper}
     * @author zhou  xun
     * @since 2024-10-29
     */

    @Override
    public ResponseWrapper editPost(PostParam postParam) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            List<SysPost> sysPostList = sysPostMapper.selectPostList(TenantContextHolder.getTenantId(), postParam.getPostCode(), null, null, null, null);
            if (null != sysPostList && !sysPostList.isEmpty()) {
                if (sysPostList.stream().anyMatch(post -> post.getPostCode().equals(postParam.getPostCode())
                        && !post.getId().equals(postParam.getId()))) {
                    result.fail("已存在相同岗位编码!");
                    return result;
                }
            }
            sysPostList = sysPostMapper.selectPostList(TenantContextHolder.getTenantId(), null, postParam.getPostName(), null, null, null);
            if (null != sysPostList && !sysPostList.isEmpty()) {
                if (sysPostList.stream().anyMatch(post -> post.getPostName().equals(postParam.getPostName())
                        && !post.getId().equals(postParam.getId()))) {
                    result.fail("已存在相同岗位名称!");
                    return result;
                }
            }
            // 验证岗位状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(postParam.getStatus());
            if (null == statusEnum) {
                result.fail("传入的岗位状态错误!");
                return result;
            }
            SysPost sysPost = PostMapStructMapper.INSTANCE.postParamToSysPost(postParam);
            sysPost.setUpdateBy(SecurityUtils.getUserId());
            sysPost.setUpdateTime(LocalDateTime.now());
            sysPostMapper.updateByPrimaryKeySelective(sysPost);
        } catch (Exception e) {
            log.error("编辑岗位时发生错误", e);
            result.fail("编辑岗位时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 编辑岗位状态
     *
     * @param id     岗位Id
     * @param status 岗位状态 0停用 1 启用
     * @return {@link ResponseWrapper}
     * @author zhou  xun
     * @since 2024-10-29
     */

    @Override
    public ResponseWrapper editPostStatus(String id, Integer status) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证岗位状态
            StatusEnum statusEnum = StatusEnum.getEnumByCode(status);
            if (null == statusEnum) {
                result.fail("传入的岗位状态错误!");
                return result;
            }
            // 验证岗位是否存在
            SysPost selectByPrimaryKey = sysPostMapper.selectByPrimaryKey(id);
            if (null == selectByPrimaryKey) {
                result.fail("传入的岗位信息不存在!");
                return result;
            }
            SysPost sysPost = new SysPost();
            sysPost.setId(id);
            sysPost.setStatus(status);
            sysPost.setUpdateBy(SecurityUtils.getUserId());
            sysPost.setUpdateTime(LocalDateTime.now());
            sysPostMapper.updateByPrimaryKeySelective(sysPost);
        } catch (Exception e) {
            log.error("编辑岗位状态时发生错误", e);
            result.fail("编辑岗位状态时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除岗位
     *
     * @param postId 岗位Id
     * @return {@link ResponseWrapper}
     * @author zhou  xun
     * @since 2024-10-29
     */
    @Override
    public ResponseWrapper deletePost(String postId) {
        ResponseWrapper result = new ResponseWrapper();
        try {
            // 验证岗位是否存在
            SysPost selectByPrimaryKey = sysPostMapper.selectByPrimaryKey(postId);
            if (null == selectByPrimaryKey) {
                result.fail("传入的岗位信息不存在!");
                return result;
            }
            //验证是否存在用户关联了岗位
            List<SysUserPost> sysUserPostList = sysUserPostMapper.selectUserPostByPostId(postId);
            if (sysUserPostList != null && !sysUserPostList.isEmpty()) {
                result.fail("该岗位已分配给用户，无法删除!");
                return result;
            }
            sysPostMapper.deleteByPrimaryKey(postId);
        } catch (Exception e) {
            log.error("删除岗位时发生错误", e);
            result.fail("删除岗位时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 查询用户的岗位id列表
     *
     * @param userId 用户Id
     * @return {@link Set<String>} 岗位id集合
     * @author zhou  xun
     * @since 2025-04-15
     */
    @Override
    public ObjectWrapper<Set<String>> selectPostIdsByUserId(String userId) {
        ObjectWrapper<Set<String>> result = new ObjectWrapper<>();
        try {
            List<SysUserPost> sysUserPostList = sysUserPostMapper.selectUserPostByUserId(userId);
            if (null != sysUserPostList && !sysUserPostList.isEmpty()) {
                Set<String> postIdSet = sysUserPostList.stream()
                        .map(SysUserPost::getPostId)
                        .collect(Collectors.toSet());
                if (!postIdSet.isEmpty()) {
                    result.setData(postIdSet);
                }
            }
        } catch (Exception e) {
            log.error("查询用户的岗位id列表时发生错误", e);
            result.fail("查询用户的岗位id列表时发生错误: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据用户ID查询岗位信息列表
     *
     * @param userId 用户ID
     * @return {@link ListWrapper<SysPost>} 岗位信息列表
     * @author zhou  xun
     */
    @Override
    public ListWrapper<SysPost> selectPostListByUserId(String userId) {
        ListWrapper<SysPost> result = new ListWrapper<>();
        try {
            List<SysPost> postList = sysUserPostMapper.selectPostListByUserId(userId);
            if (postList != null && !postList.isEmpty()) {
                result.setData(postList);
            }
        } catch (Exception e) {
            log.error("根据用户ID查询岗位信息列表时发生错误", e);
            result.fail("查询岗位信息时发生错误: " + e.getMessage());
        }
        return result;
    }

    @Override
    public ListWrapper<SysPostVO> selectPostVOList(PostParam postParam) {
        // 获取岗位列表
        ListWrapper<SysPost> listWrapper = selectPostList(postParam);

        // 验证请求是否成功
        if (listWrapper.verifyFail()) {
            ListWrapper<SysPostVO> result = new ListWrapper<>();
            result.fail(listWrapper.getMsg());
            return result;
        }


        // 创建结果包装对象并设置数据
        ListWrapper<SysPostVO> result = new ListWrapper<>();
        if (null != listWrapper.getData() && !listWrapper.getData().isEmpty()) {
            // 转换并处理数据
            List<SysPostVO> processedData = listWrapper.getData().stream()
                    .map(PostMapStructMapper.INSTANCE::sysPostToSysPostVO)
                    .collect(Collectors.toList());
            result.setData(processedData);
        }
        return result;
    }

    /**
     * 根据用户ID查询岗位信息VO列表
     *
     * @param userId 用户ID
     * @return {@link ListWrapper<SysPostVO>} 岗位信息VO列表
     * @author zhou  xun
     */
    @Override
    public ListWrapper<SysPostVO> selectPostVOListByUserId(String userId) {
        // 获取岗位列表
        ListWrapper<SysPost> listWrapper = selectPostListByUserId(userId);

        // 验证请求是否成功
        if (listWrapper.verifyFail()) {
            ListWrapper<SysPostVO> result = new ListWrapper<>();
            result.fail(listWrapper.getMsg());
            return result;
        }
        // 创建结果包装对象并设置数据
        ListWrapper<SysPostVO> result = new ListWrapper<>();
        if (null != listWrapper.getData() && !listWrapper.getData().isEmpty()) {
            // 转换并处理数据
            List<SysPostVO> processedData = listWrapper.getData().stream()
                    .map(PostMapStructMapper.INSTANCE::sysPostToSysPostVO)
                    .collect(Collectors.toList());
            result.setData(processedData);
        }
        return result;
    }

    @Override
    public PageWrapper<SysPostVO> selectPostVOListByPage(PostParam postParam) {
        // 获取岗位列表
        PageWrapper<SysPost> pageWrapper = selectPostListByPage(postParam);

        // 验证请求是否成功
        if (pageWrapper.verifyFail()) {
            PageWrapper<SysPostVO> result = new PageWrapper<>();
            result.fail(pageWrapper.getMsg());
            return result;
        }
        // 创建结果包装对象并设置数据
        PageWrapper<SysPostVO> result = new PageWrapper<>();
        if (null != pageWrapper.getData() && !pageWrapper.getData().isEmpty()) {
            // 转换并处理数据
            List<SysPostVO> processedData = pageWrapper.getData().stream()
                    .map(PostMapStructMapper.INSTANCE::sysPostToSysPostVO)
                    .collect(Collectors.toList());
            result.setData(processedData);
            result.setTotal(pageWrapper.getTotal());
            result.setCurrentPageNum(pageWrapper.getCurrentPageNum());
            result.setTotalPage(pageWrapper.getPageSize());
        }
        return result;
    }
}